package com.lhb.user.controller;

import com.lhb.common.model.UnifyResponseObject;
import com.lhb.user.constant.Sender;
import com.lhb.user.model.*;
import com.lhb.user.service.AuthService;
import com.lhb.user.service.EmailService;
import com.lhb.user.utils.CodeUtil;
import com.lhb.user.utils.RandomGenerator;
import jakarta.mail.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;

/**
 * @author 86131
 * @version 1.0
 * @description
 * @date 2025/7/23 下午7:41
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private CodeUtil codeUtil;
    @Autowired
    private EmailService emailService;
    @Autowired
    private AuthService authService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //邮箱验证码发送
    @PostMapping("/email/send-code")
    public UnifyResponseObject<String> getEmailCaptcha(@RequestBody SendCodeRequest sendCodeRequest)
    {
        String code = RandomGenerator.generateCode(6);
        //todo 判断上一次发送验证码是否已过60秒
        boolean flag = codeUtil.saveCode(sendCodeRequest.getEmail(), code, Sender.EmailVerificationCode);
        //todo 过了重发
        if(flag)
        {
            rabbitTemplate.convertAndSend("email.direct","code",new SendCodeModel(sendCodeRequest.getEmail(),code));
            return UnifyResponseObject.success("验证码已发送");

        }
        //todo 没过返回友好提示
        return UnifyResponseObject.success("请不要频繁请求验证码，稍后再试");
    }

    @PostMapping("/email/reset-password")
    @Transactional
    public UnifyResponseObject ResetPassword(@RequestBody ResetPasswordRequest resetPasswordRequest)
    {

        authService.ResetPassword(resetPasswordRequest);
        return UnifyResponseObject.success("新密码已发送到您的邮箱");

    }

    @PostMapping("/register")
    public UnifyResponseObject register(@RequestBody RegisterModel registerModel)
    {
            authService.register(registerModel);
            return UnifyResponseObject.success("注册成功");
    }

    @PostMapping("/login")
    public UnifyResponseObject<LoginVO> login(@RequestBody LoginModel loginModel) throws Exception {

        LoginVO loginVO = authService.login(loginModel);


        return UnifyResponseObject.success(loginVO,"登录成功，欢迎回来");
    }




}
